import axios from "axios";
import { ElMessage } from "element-plus";

// const baseURL = 'http://192.168.0.44:8090'
// const baseURL = 'http://localhost:8090'
const baseURL = () => {
  // 测试环境的接口域名
  if (window.location.hostname === "localhost") {
    return "http://localhost:8090";
  }
  // 生产环境的接口域名
  return "http://192.168.0.44:8090";
};

const headers = {
  Authorization: "",
};

const instance = axios.create({
  baseURL: baseURL(),
  headers,
});

const token = localStorage.getItem("Authorization");

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    config.headers.Authorization = token;
    return config;
  },
  (err) => {
    alert(err);
    return Promise.reject(err);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  (result) => {
    if (result.status !== 200) {
      window.location.href = "/login";
    }

    return result.data;
  },
  (err) => {
    if (err.status == 401) {
      window.location.href = "/login";
    } else {
      alert(err);
    }
    return Promise.reject(err);
  }
);

export default instance;
